package com.hjb.service.utils;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * 获取交易日
 * @author zhangxl
 * @date 2017-07-26
 * @version 1.0
 */
public class TradeDateUtil {
	
	public static SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-dd");
	
	public static String getDayAfterHoliday(String nextDay, List<String> holidayList) {
        if(null  != holidayList) {
            for(int  i = 0; i < holidayList.size(); i++) {
                if(holidayList.get(i).equals(nextDay)) {
                    nextDay = getDayAfterHoliday(getNextDay(nextDay), holidayList);
                }
            }
        }
        nextDay = getDayExceptWeekend(nextDay);
        return  nextDay;
	 }
	 
	/**
     * 获取下一天
     * 
     * @param day 当前日期yyyyMMdd
     * @return
     */
    public static String getNextDay(String day) {
        Calendar cal = formatYYYYMMDD(day);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        return sdf.format(cal.getTime());
    }
	    
	/**
     * 如果当前日期处于周末，则返回下周一
     * 
     * @param day 当前日期yyyyMMdd
     * @return
     */
    public static String getDayExceptWeekend(String day) {
        Calendar cal = formatYYYYMMDD(day);
        if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            cal.add(Calendar.DAY_OF_MONTH, 2);
        }else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
//        }else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
//            cal.add(Calendar.DAY_OF_MONTH, 3);
//        } 
        return sdf.format(cal.getTime());
    }

    /**
     * 将字符串类型日期转换为Calendar
     * 
     * @param day 当前日期yyyyMMdd
     * @return
     */
    public static Calendar formatYYYYMMDD(String day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day.substring(0, 4)), (Integer.parseInt(day.substring(5, 7)))-1 , Integer.parseInt(day.substring(8)));
        return cal;
    }
    
    
    public static void main(String[] args) {
		String nextDay =getDayExceptWeekend("2017-09-29") ;
		System.out.println(nextDay);
//        // 时间必须要从小到大排序，否则会出问题
        String[] a = {"2017-10-01", "2017-10-02", "2017-10-03", "2017-10-04", "2017-10-05", "2017-10-06", "2017-10-07", "2017-10-08"};
        List<String> holidayList = Arrays.asList(a);
        System.out.println("有效的最近交易日nextDay:"  + getDayAfterHoliday(nextDay, holidayList));

       
	}

}
